<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="box1">开始</button>
    <button id="box2">结束</button>
    <span id="box">Tom</span>
    <script>
        //获取页面中的元素
        var btn1 = document.getElementById("box1");
        var btn2 = document.getElementById("box2");
        var span = document.getElementById("box");
        var names = ['Tom', 'Jack', 'Lily', 'Peter'];
        var timer;
        btn1.onclick = function() {
            //使用定时器前先清除定时器
            window.clearTimeout(timer);
            timer = window.setInterval(countName, 100)

        }
        btn2.onclick = function() {
            window.clearInterval(timer);
        }

        function countName() {
            var index = parseInt(Math.random() * names.length);
            span.innerHTML = names[index];
        }
    </script>
</body>

</html>